/**
 *
 */
package org.suren.littlebird.actions.bundle;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.action.Action;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableItem;
import org.suren.littlebird.actions.Reload;

/**
 * @author suren
 * @since 2015-2-5
 */
public class AbstractSuRenBundleSyncAction extends Action
{
	public void control(final Table table, final SuRenBundleController controller, final Reload bundleReload, final int action)
	{
		TableItem[] selectionItems = table.getSelection();
		if(selectionItems == null || selectionItems.length == 0)
		{
			return;
		}

		final long[] ids = new long[selectionItems.length];
		for(int i = 0; i < selectionItems.length; i++)
		{
			try
			{
				ids[i] = Long.parseLong(selectionItems[i].getText(0));
			}
			catch(NumberFormatException e){}
		}

		new Job("Bundle Control"){

			@Override
			protected IStatus run(IProgressMonitor arg0)
			{

				final int count = controller.control(action, null, ids);

				Display.getDefault().syncExec(new Runnable()
				{

					@Override
					public void run()
					{
						if(count > 0)
						{
							bundleReload.reload(null, null);
						}
					}
				});

				return Status.OK_STATUS;
			}
		}.schedule();
	}
}
